<template>
  <div class="batch-management">
    <div class="header-actions">
      <el-button type="primary" @click="dialogVisible = true">新增</el-button>
      <el-button
        type="danger"
        @click="handleDelete()"
        :disabled="!selectedRows.length"
        >删除</el-button
      >
    </div>

    <el-table
      ref="tableRef"
      :data="processedTableData"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
    >
      <!-- 选择列 -->
      <el-table-column
        type="selection"
        width="55"
        :selectable="(row: TableRecord) => !row._isSearchRow"
      >
        <template #default="{ row }">
          <template v-if="row._isSearchRow">
            <!-- 搜索行不显示复选框 -->
            <div style="width: 100%; height: 100%"></div>
          </template>
        </template>
        <template #header>
          <el-checkbox
            v-model="isAllSelected"
            :indeterminate="isIndeterminate"
            @change="handleSelectAll"
          />
        </template>
      </el-table-column>

      <!-- 序号列 -->
      <el-table-column label="序号" type="index" width="60px">
        <template #default="{ row, $index }">
          <template v-if="row._isSearchRow">
            <!-- 搜索行显示空白 -->
            <div style="height: 28px"></div>
          </template>
          <template v-else>
            {{ $index }}
          </template>
        </template>
      </el-table-column>

      <!-- 商品名称列 -->
      <el-table-column label="商品名称" prop="goodsName" width="100px">
        <template #default="{ row }">
          <el-input
            v-if="row._isSearchRow"
            v-model="searchForm.goodsName"
            placeholder="请输入商品名称"
            clearable
            @input="handleSearch"
          />
          <span v-else>{{ row.goodsName }}</span>
        </template>
      </el-table-column>

      <!-- 生产批次列 -->
      <el-table-column label="生产批次" prop="production_Batch" width="170px">
        <template #default="{ row }">
          <el-input
            v-if="row._isSearchRow"
            v-model="searchForm.production_Batch"
            placeholder="请输入生产批次"
            clearable
            @input="handleSearch"
          />
          <span v-else>{{ row.production_Batch }}</span>
        </template>
      </el-table-column>

      <!-- 保质期列 -->
      <el-table-column
        label="保质期(天)"
        prop="quality_Guarantee"
        width="100px"
      >
        <template #default="{ row }">
          <el-input
            v-if="row._isSearchRow"
            v-model="searchForm.quality_Guarantee"
            placeholder="请输入保质期"
            clearable
            @input="handleSearch"
          />
          <span v-else>{{ row.quality_Guarantee }}</span>
        </template>
      </el-table-column>

      <!-- 生产许可证号列 -->
      <el-table-column
        label="生产许可证号"
        prop="production_License"
        width="120px"
      >
        <template #default="{ row }">
          <el-input
            v-if="row._isSearchRow"
            v-model="searchForm.production_License"
            placeholder="请输入生产许可证号"
            clearable
            @input="handleSearch"
          />
          <span v-else>{{ row.production_License }}</span>
        </template>
      </el-table-column>

      <!-- 生产企业列 -->
      <el-table-column
        label="生产企业"
        prop="manufacturing_Enterprise"
        width="100px"
      >
        <template #default="{ row }">
          <el-input
            v-if="row._isSearchRow"
            v-model="searchForm.manufacturing_Enterprise"
            placeholder="请输入生产企业"
            clearable
            @input="handleSearch"
          />
          <span v-else>{{ row.manufacturing_Enterprise }}</span>
        </template>
      </el-table-column>

      <!-- 信息完整度列 -->
      <el-table-column
        label="信息完整度"
        prop="information_Completeness"
        width="100px"
      >
        <template #default="{ row }">
          <template v-if="row._isSearchRow">
            <!-- 搜索行显示空白 -->
            <div style="height: 28px"></div>
          </template>
          <template v-else>
            <div
              :style="{
                color: getCompletenessColor(row.information_Completeness),
              }"
            >
              {{ row.information_Completeness.toFixed(2) }}%
            </div>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="封面图" width="100px">
        <template #default="{ row }">
          <template v-if="!row._isSearchRow">
            <el-image
              v-if="row.cover_Image"
              :src="row.cover_Image"
              :preview-src-list="[row.cover_Image]"
              fit="cover"
              style="width: 50px; height: 50px"
            />
            <span v-else>暂无图片</span>
          </template>
        </template>
      </el-table-column>
      <!-- 创建人列 -->
      <el-table-column label="创建人" prop="creator" width="100px">
        <template #default="{ row }">
          <el-input
            v-if="row._isSearchRow"
            v-model="searchForm.creator"
            placeholder="请输入创建人"
            clearable
            @input="handleSearch"
          />
          <span v-else>{{ row.creator }}</span>
        </template>
      </el-table-column>

      <!-- 创建时间列 -->
      <el-table-column label="创建时间" width="180px">
        <template #default="{ row }">
          <el-input
            v-if="row._isSearchRow"
            v-model="searchForm.createTime"
            placeholder="请输入创建时间"
            clearable
            @input="handleSearch"
          />
          <span v-else>{{
            row.createTime
              ? moment(row.createTime).format("YYYY-MM-DD HH:mm:ss")
              : "-"
          }}</span>
        </template>
      </el-table-column>

      <!-- 修改人列 -->
      <el-table-column label="修改人" prop="reviser" width="100px">
        <template #default="{ row }">
          <el-input
            v-if="row._isSearchRow"
            v-model="searchForm.reviser"
            placeholder="请输入修改人"
            clearable
            @input="handleSearch"
          />
          <span v-else>{{ row.reviser }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="180px">
        <template #default="{ row }">
          <el-input
            v-if="row._isSearchRow"
            v-model="searchForm.updateTime"
            placeholder="请输入修改时间"
            clearable
            @input="handleSearch"
          />
          <span v-else>{{
            row.updateTime
              ? moment(row.updateTime).format("YYYY-MM-DD HH:mm:ss")
              : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop=" " label="操作" width="350px" fixed="right">
        <template #default="{ row }">
          <template v-if="!row._isSearchRow">
            <el-button type="primary" @click="handleDetail(row)"
              >详情</el-button
            >
            <el-button type="warning" @click="handleModify(row)"
              >修改</el-button
            >
            <el-button type="success" @click="handleExport(row)"
              >导出溯码</el-button
            >
            <el-button type="danger" @click="handleDelete(row.production_Batch)"
              >删除</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>

    <table>
      <tr>
        <td>
          <el-pagination
            v-model:current-page="page.pageindex"
            v-model:page-size="page.pagesize"
            :page-sizes="[15, 20, 30]"
            :size="size"
            background="true"
            layout="slot, sizes"
            :total="page.totalCount"
          >
            共{{ page.totalCount }}条 每页显示{{ page.pagesize }}条 当前第{{
              page.pageindex
            }}页/共{{ page.totalPage }}页
          </el-pagination>
        </td>
        <td>
          <el-pagination
            v-model:current-page="page.pageindex"
            v-model:page-size="page.pagesize"
            :page-sizes="[15, 20, 30]"
            :size="size"
            background="true"
            layout="slot, prev, pager, next"
            :total="page.totalCount"
            prev-text="上一页"
            next-text="下一页"
          >
            <el-button
              :disabled="page.pageindex == 1"
              @click="page.pageindex = 1"
              >首页</el-button
            >
          </el-pagination>
        </td>
        <td>
          <el-pagination
            v-model:current-page="page.pageindex"
            v-model:page-size="page.pagesize"
            :page-sizes="[15, 20, 30]"
            :size="size"
            background="true"
            layout="slot,jumper"
            :total="page.totalCount"
          >
            <el-button
              :disabled="page.pageindex == page.totalPage"
              @click="page.pageindex = page.totalPage"
              >尾页</el-button
            >
          </el-pagination>
        </td>
      </tr>
    </table>

    <el-dialog
      :title="dialogType === 'add' ? '新增溯源管理' : '修改溯源管理'"
      v-model="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
      >
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-form-item label="商品名称" prop="goodsId" required>
            <el-select
              v-model="ruleForm.goodsId"
              placeholder="请选择商品名称"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in goodsList"
                :key="item.id"
                :label="item.goodsName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="生产批次" prop="production_Batch" required>
            <el-input
              v-model="ruleForm.production_Batch"
              placeholder="系统自动生成"
              readonly
              disabled
            />
            <div class="form-item-tip">系统根据时间自动生成唯一批次号</div>
          </el-form-item>

          <el-form-item label="保质期(天)" prop="quality_Guarantee" required>
            <el-input
              v-model="ruleForm.quality_Guarantee"
              placeholder="请输入保质期"
              maxlength="5"
              show-word-limit
              @input="handleShelfLifeInput"
            />
          </el-form-item>

          <el-form-item label="生产许可证号" prop="production_License" required>
            <el-input
              v-model="ruleForm.production_License"
              placeholder="请输入生产许可证号"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>

          <el-form-item
            label="生产企业"
            prop="manufacturing_Enterprise"
            required
          >
            <el-input
              v-model="ruleForm.manufacturing_Enterprise"
              placeholder="请输入生产企业"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="封面图" prop="cover_Image">
            <el-upload
              class="avatar-uploader"
              action="https://localhost:7008/api/Img/Photo"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="ruleForm.cover_Image"
                :src="ruleForm.cover_Image"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </div>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            {{ dialogType === "add" ? "保存" : "修改" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 导出设置弹出框 -->
    <el-dialog
      title="导出设置"
      v-model="exportDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      @close="handleExportDialogClose"
    >
      <el-form
        ref="exportFormRef"
        :model="exportForm"
        :rules="exportRules"
        label-width="100px"
      >
        <el-form-item label="导出数量" prop="exportCount" required>
          <el-input
            v-model="exportForm.exportCount"
            placeholder="请输入导出数量"
            maxlength="4"
            @input="handleExportCountInput"
          >
            <template #append>张</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="confirmExport">打印</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, computed } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import type { UploadProps } from "element-plus";
import axios from "axios";
import { type ComponentSize } from "element-plus";
import moment from "moment";
import QRCode from "qrcode";

interface TableRecord {
  id: number;
  goodsId: number;
  goodsName: string;
  production_Batch: string;
  quality_Guarantee: number;
  production_License: string;
  manufacturing_Enterprise: string;
  information_Completeness: number;
  cover_Image: string;
  createTime: string | null;
  creator: string | null;
  updateTime: string | null;
  reviser: string | null;
  _isSearchRow?: boolean; // 添加搜索行标识
}

interface GoodsItem {
  id: number;
  goodsName: string;
}

// 定义搜索表单的接口
interface SearchForm {
  goodsName: string;
  production_Batch: string;
  quality_Guarantee: string;
  production_License: string;
  manufacturing_Enterprise: string;
  createTime: string;
  creator: string;
  updateTime: string;
  reviser: string;
  [key: string]: string;
}

const router = useRouter();
const size = ref<ComponentSize>("default");

// 表格数据
const tableData = ref<TableRecord[]>([]);
const selectedRows = ref<TableRecord[]>([]);

// 对话框控制
const dialogVisible = ref(false);
const dialogType = ref<"add" | "modify">("add");

// 搜索表单数据
const searchForm = reactive<SearchForm>({
  goodsName: "",
  production_Batch: "",
  quality_Guarantee: "",
  production_License: "",
  manufacturing_Enterprise: "",
  createTime: "",
  creator: "",
  updateTime: "",
  reviser: "",
});

// 表格数据处理，添加搜索行
const processedTableData = computed(() => {
  // 创建搜索行
  const searchRow = {
    id: -1,
    goodsId: -1,
    goodsName: searchForm.goodsName,
    production_Batch: searchForm.production_Batch,
    quality_Guarantee: searchForm.quality_Guarantee,
    production_License: searchForm.production_License,
    manufacturing_Enterprise: searchForm.manufacturing_Enterprise,
    information_Completeness: 0,
    cover_Image: "",
    createTime: searchForm.createTime,
    creator: searchForm.creator,
    updateTime: searchForm.updateTime,
    reviser: searchForm.reviser,
    _isSearchRow: true,
  };

  // 将搜索行添加到数据的开头
  return [searchRow, ...tableData.value];
});

// 商品列表
const goodsList = ref<GoodsItem[]>([]);

// 分页参数
const page = reactive({
  pageindex: 1,
  pagesize: 15,
  totalCount: 0,
  totalPage: 0,
});

// 表单数据
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  goodsId: "",
  production_Batch: "",
  quality_Guarantee: "",
  production_License: "",
  manufacturing_Enterprise: "",
  information_Completeness: "",
  cover_Image: "",
});

// 表单验证规则
const rules = reactive<FormRules>({
  goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],
  production_Batch: [
    { required: true, message: "请输入生产批次", trigger: "blur" },
    { max: 30, message: "最多支持输入30个字符", trigger: "blur" },
  ],
  quality_Guarantee: [
    { required: true, message: "请输入保质期", trigger: "blur" },
    {
      pattern: /^\d{1,5}$/,
      message: "只允许输入数字，最多5位",
      trigger: "blur",
    },
  ],
  production_License: [
    { required: true, message: "请输入生产许可证号", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{1,30}$/,
      message: "只允许输入数字、字母",
      trigger: "blur",
    },
    { max: 30, message: "最多支持输入30个字符", trigger: "blur" },
  ],
  manufacturing_Enterprise: [
    { required: true, message: "请输入生产企业", trigger: "blur" },
    {
      pattern: /^[a-zA-Z\u4e00-\u9fa5]{1,30}$/,
      message: "只允许输入汉字和字母",
      trigger: "blur",
    },
    { max: 30, message: "最多支持输入30个字符", trigger: "blur" },
  ],
});

// 监听dialogVisible的变化
watch(dialogVisible, (newVal) => {
  if (newVal && dialogType.value === "add") {
    ruleForm.production_Batch = generateBatchNumber();
  }
});

// 生成批次号
const generateBatchNumber = () => {
  const now = new Date();
  const date = now.toISOString().slice(0, 10).replace(/-/g, "");
  const time = now.toTimeString().slice(0, 8).replace(/:/g, "");
  const random = Math.random().toString(36).substring(2, 6).toUpperCase();
  return `${date}${time}-${random}`;
};

// 搜索处理函数
const handleSearch = () => {
  // 构建查询参数
  const params = {
    pageindex: page.pageindex,
    pagesize: page.pagesize,
    ...searchForm,
  };

  // 调用后端API进行查询
  axios({
    url: "https://localhost:7008/api/Basic/GetBasic_Traceability",
    method: "get",
    params: params,
  })
    .then((res) => {
      if (res.data.code === 200) {
        tableData.value = res.data.pageDatas;
        page.totalCount = res.data.totalCount;
        page.totalPage = res.data.totalPage;
      } else {
        ElMessage.error(res.data.msg || "查询失败");
      }
    })
    .catch((error) => {
      console.error("查询失败:", error);
      ElMessage.error("查询失败，请稍后重试");
    });
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach((key: string) => {
    if (key in searchForm) {
      searchForm[key] = "";
    }
  });
  handleSearch();
};

// 页面加载时执行
onMounted(() => {
  getGoods();
  handleSearch(); // 初始化时也进行一次搜索
});

// 获取表格数据
const search = () => {
  axios({
    url: "https://localhost:7008/api/Basic/GetBasic_Traceability",
    method: "get",
    params: {
      pageindex: page.pageindex,
      pagesize: page.pagesize,
    },
  }).then((res) => {
    if (res.data.code === 200) {
      tableData.value = res.data.pageDatas;
      page.totalCount = res.data.totalCount;
      page.totalPage = res.data.totalPage;
    } else {
      ElMessage.error(res.data.msg || "获取数据失败");
    }
  });
};

// 获取商品列表
const getGoods = () => {
  axios({
    url: "https://localhost:7008/api/Basic/GetGoods",
    method: "get",
  }).then((res) => {
    if (res.data.code === 200) {
      goodsList.value = res.data.data;
    } else {
      ElMessage.error(res.data.msg || "获取商品列表失败");
    }
  });
};

// 修改
const handleModify = (row: TableRecord) => {
  dialogType.value = "modify";
  // 深拷贝数据，避免直接修改表格数据
  Object.assign(ruleForm, JSON.parse(JSON.stringify(row)));
  dialogVisible.value = true;
};

// 详情
const handleDetail = (row: any) => {
  router.push({
    path: "/batch-detail",
    query: {
      production_Batch: row.production_Batch,
    },
  });
};

// 导出设置相关
const exportDialogVisible = ref(false);
const exportFormRef = ref<FormInstance>();
const exportForm = reactive({
  exportCount: "",
  currentRow: null as any,
});

// 导出表单验证规则
const exportRules = reactive<FormRules>({
  exportCount: [
    { required: true, message: "请输入导出数量", trigger: "blur" },
    { pattern: /^\d{1,4}$/, message: "只能输入1-4位数字", trigger: "blur" },
  ],
});

// 处理导出数量输入
const handleExportCountInput = (value: string) => {
  // 只允许输入数字，且最多4位
  exportForm.exportCount = value.replace(/\D/g, "").slice(0, 4);
};

// 处理导出按钮点击
const handleExport = async (row: any) => {
  exportForm.currentRow = row;
  exportForm.exportCount = exportForm.exportCount || ""; // 保持上次输入的数量
  exportDialogVisible.value = true;
};

// 执行导出操作
const executeExport = async (row: any, count: number) => {
  try {
    // 创建二维码内容对象
    const qrContent = {
      production_Batch: row.production_Batch,
      goodsName: row.goodsName,
      manufacturing_Enterprise: row.manufacturing_Enterprise,
      production_License: row.production_License,
      quality_Guarantee: row.quality_Guarantee,
      printCount: count,
    };

    // 将对象转换为JSON字符串
    const qrString = JSON.stringify(qrContent);

    // 生成二维码图片的DataURL
    const qrDataUrl = await QRCode.toDataURL(qrString, {
      width: 300,
      margin: 2,
      color: {
        dark: "#000000",
        light: "#ffffff",
      },
    });

    // 创建一个临时链接来下载二维码
    const link = document.createElement("a");
    link.download = `溯源码_${row.production_Batch}_${count}张.png`;
    link.href = qrDataUrl;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success(`成功导出${count}张溯源码`);
    exportDialogVisible.value = false;
  } catch (error) {
    console.error("生成二维码失败:", error);
    ElMessage.error("溯源码导出失败，请重试");
  }
};

// 处理弹窗关闭
const handleExportDialogClose = () => {
  if (exportFormRef.value) {
    exportFormRef.value.resetFields();
  }
};

// 确认导出
const confirmExport = async () => {
  if (!exportFormRef.value) return;

  await exportFormRef.value.validate(async (valid) => {
    if (valid) {
      const count = parseInt(exportForm.exportCount);
      const row = exportForm.currentRow;
      await executeExport(row, count);
    }
  });
};

// 全选相关的状态
const isAllSelected = ref(false);
const isIndeterminate = ref(false);

// 处理全选
const handleSelectAll = (val: boolean) => {
  const table = tableRef.value;
  if (table) {
    // 获取所有非搜索行
    const rows = processedTableData.value.filter((row) => !row._isSearchRow);
    rows.forEach((row) => {
      table.toggleRowSelection(row, val);
    });
    isIndeterminate.value = false;
  }
};

// 表格选择变化
const handleSelectionChange = (selection: TableRecord[]) => {
  // 过滤掉搜索行
  selectedRows.value = selection.filter((row) => !row._isSearchRow);

  // 更新全选状态
  const totalRows = tableData.value.length;
  const selectedCount = selectedRows.value.length;

  isIndeterminate.value = selectedCount > 0 && selectedCount < totalRows;
  isAllSelected.value = selectedCount === totalRows && totalRows > 0;
};

// 表格ref
const tableRef = ref();

// 删除（支持批量删除和单行删除）
const handleDelete = (production_Batch?: string) => {
  const isBatchDelete = !production_Batch;

  // 检查选中状态
  if (
    isBatchDelete &&
    (!selectedRows.value || selectedRows.value.length === 0)
  ) {
    ElMessage.warning("请选择要删除的记录");
    return;
  }

  // 获取要删除的批次号
  const batchesToDelete = isBatchDelete
    ? selectedRows.value.map((row) => row.production_Batch)
    : [production_Batch];

  // 打印日志以便调试
  console.log("要删除的批次:", batchesToDelete);
  console.log("是否批量删除:", isBatchDelete);

  const message = isBatchDelete
    ? `确认删除选中的 ${batchesToDelete.length} 条记录?`
    : "确认删除该条记录?";

  ElMessageBox.confirm(message, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 将数组转换为逗号分隔的字符串
      const production_Batchlist = batchesToDelete.join(",");

      console.log("发送到后端的批次列表:", production_Batchlist);

      axios({
        url: "https://localhost:7008/api/Basic/DeleteBasic_Traceability",
        method: "delete",
        params: {
          production_Batchlist: production_Batchlist,
        },
      })
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.msg);
            search();
            // 清空选中行
            selectedRows.value = [];
          } else {
            ElMessage.error(res.data.msg);
          }
        })
        .catch((error) => {
          console.error("删除请求失败:", error);
          ElMessage.error("删除失败，请稍后重试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 图片上传成功
const handleAvatarSuccess = (response: any) => {
  ruleForm.cover_Image = response;
};

// 图片上传前校验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (file) => {
  if (file.type !== "image/jpeg") {
    ElMessage.error("您上传的不是图片!");
    return false;
  }
  if (file.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能大于2MB!");
    return false;
  }
  return true;
};

// 保质期输入处理
const handleShelfLifeInput = (value: string) => {
  ruleForm.quality_Guarantee = value.replace(/\D/g, "").slice(0, 5);
};

// 提交表单(新增和修改)
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      const submitData = {
        ...ruleForm,
        information_Completeness: 0, // 直接设置为0
      };

      const url =
        dialogType.value === "add"
          ? "https://localhost:7008/api/Basic/CreateBasic_Traceability"
          : "https://localhost:7008/api/Basic/UpdateBasic_Traceability";

      axios({
        url,
        method: dialogType.value === "add" ? "post" : "put",
        data: submitData,
      }).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(
            dialogType.value === "add" ? "添加成功" : "修改成功"
          );
          dialogVisible.value = false;
          search();
          // 重置表单
          resetForm(formEl);
        } else {
          ElMessage.error(
            res.data.msg ||
              (dialogType.value === "add" ? "添加失败" : "修改失败")
          );
        }
      });
    }
  });
};

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  // 如果是修改模式，重置后切换回添加模式
  if (dialogType.value === "modify") {
    dialogType.value = "add";
  }
};

// 监听对话框关闭
const handleDialogClose = () => {
  resetForm(ruleFormRef.value);
  // 手动清空表单数据
  ruleForm.goodsId = "";
  ruleForm.production_Batch = "";
  ruleForm.quality_Guarantee = "";
  ruleForm.production_License = "";
  ruleForm.manufacturing_Enterprise = "";
  ruleForm.information_Completeness = "";
  ruleForm.cover_Image = "";
  dialogType.value = "add";
};

// 获取完整度颜色
const getCompletenessColor = (value: number): string => {
  if (value >= 100) return "#67C23A"; // 绿色
  if (value >= 60) return "#E6A23C"; // 橙色
  return "#F56C6C"; // 红色
};
</script>

<style scoped>
.batch-management {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.form-section {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  position: relative;
  padding-left: 10px;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #409eff;
}

.form-item-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.2;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

:deep(.el-table .search-row) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-input__inner) {
  height: 28px;
  line-height: 28px;
  padding: 0 8px;
}

:deep(.el-table .el-input) {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
